package com.jtpay.unionpay.product.utils;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import com.jtpay.unionpay.product.DaoMaster;
import com.jtpay.unionpay.product.DaoSession;
import com.jtpay.unionpay.product.utils.manager.AppManager;
import com.jtpay.unionpay.product.utils.manager.PageManagement;
import org.greenrobot.greendao.database.Database;

/**
 * Created by lj on 2018/1/11 0011.
 */

public class AppApplication extends Application {
    protected static Context mContext;
    /**
     * A flag to show how easily you can switch from standard SQLite to the encrypted SQLCipher.
     */
    public static final boolean ENCRYPTED = false;

    private DaoSession daoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        init();
        mContext = getApplicationContext();
        AppManager.init(mContext);
        registerActivityListener();
    }

    private void init() {
        DaoMaster.DevOpenHelper helper =
                new DaoMaster.DevOpenHelper(
                        this, ENCRYPTED ? "up-qr-db-encrypted" : "up-qr-db");
        Database db = ENCRYPTED ?
                helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();
        daoSession = new DaoMaster(db).newSession();
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }

    public static Context getContext() {
        return mContext;
    }

    private void registerActivityListener() {
        //api 4.0开始才可使用
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                /*
                 *  监听到 Activity创建事件 将该 Activity 加入list
                 */
                PageManagement.getInstance().pushAC(activity);
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                PageManagement.getInstance().removeAC(activity);
            }
        });
    }
}
